package com.haidechizi.fastadmin.common.type;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author wangdejun
 */
public class ListTypeHandler extends BaseTypeHandler<List<?>> {


    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<?> objects, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JSON.toJSONString(objects));
    }

    @Override
    public List<?> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return getResult(resultSet.getString(s));
    }

    @Override
    public List<?> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return getResult(resultSet.getString(i));
    }

    @Override
    public List<?> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return getResult(callableStatement.getString(i));
    }

    private List<?> getResult(String object) {
        return JSON.parseArray(object);
    }
}
